package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.config.BaseContext;
import com.itheima.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class CheckFilter implements Filter {

    //Spring提供的一个路径匹配器，支持通配符，用来比较两个路径是否相同
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //1.获得当前访问路径
        String requestURI = req.getRequestURI();

        //这些路径无需拦截，可直接访问
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        //2.判断该访问路径是否应该被拦截
        for (String url : urls) {
            if (PATH_MATCHER.match(url, requestURI)) {
                //访问的是无需拦截的，直接放行,终止方法
                filterChain.doFilter(req, resp);
                return;
            }
        }

        //3.访问了需要权限的业务，检查本次访问是否已登录
        if (null != req.getSession().getAttribute("employee")) {
            Long empId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            //说明当前是已登录状态，正常放行，终止方法
            filterChain.doFilter(req, resp);
            return;
        }

        //4-2、判断登录状态，如果已登录，则直接放行
        if (req.getSession().getAttribute("user") != null) {
            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            //说明当前是已登录状态，正常放行，终止方法
            filterChain.doFilter(req, resp);
            return;
        }

        //4.走到这里，说明这是一次未登录的访问行为，告知其需登录后才能访问
        //写NOTLOGIN是因为在前端页面（request.js）中，定义了一个响应拦截器，当受到NOTLOGIN这个信息时，就会跳转到登录页面
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
}
